package com.example.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 用 Linux 的 ps 命令列出系统当前运行的所有进程，
 * 
 * @author  2014-8-5
 *
 */
public class NativeProcessScaner {

    public static final class NProc {
        public String user;
        public int pid;
        public int ppid; //父进程id
        public int vsize;
        public int rss;
        public int wchan;
        public int pc;
        public String processName;
        public boolean chkedTag;
        
        
        public NProc(String user, int pid, int ppid, int vsize, int rss, int wchan, int pc,
                String name) {
            this.user = user;
            this.pid = pid;
            this.ppid = ppid;
            this.vsize = vsize;
            this.rss = rss;
            this.wchan = wchan;
            this.pc = pc;
            this.processName = name;
        }


		@Override
		public String toString() {
			StringBuilder builder = new StringBuilder();
			builder.append("NProc [\n\tuser=").append(user)
					.append(", \n\tname=").append(processName)
					.append(", \n\tpid=").append(pid).append(", \n\tppid=")
					.append(ppid).append(", \n\tvsize=").append(vsize)
					.append(", \n\trss=").append(rss).append(", \n\twchan=")
					.append(wchan).append(", \n\tpc=").append(pc)
					.append("\n]");
			return builder.toString();
		}
        
    }
    
    private static int toInt(String s) {
        return toInt(s, false);
    }
    
    private static int toInt(String s, boolean hex) {
        try {
            return Integer.parseInt(s, hex? 16 : 10);
        } catch (Exception e) {
        }
        
        return 0;
    }

    public static List<NProc> scanProcess() {
        List<String> list = Shell.runCmdAndGetResult("ps");
        
        if(list != null) {
            final int N = list.size();
            List<NProc> procs = new ArrayList<NProc>(N);

            for(int i=1; i<N; i++) {
                String[] ss = list.get(i).split("\\s+");
                
                NProc proc = new NProc(ss[0], 
                        toInt(ss[1]),
                        toInt(ss[2]),
                        toInt(ss[3]),
                        toInt(ss[4]),
                        toInt(ss[5], true),
                        toInt(ss[6], true),
                        ss[8]);
                procs.add(proc);
            }
            
            return procs;
        }
        
        return null;
    }
    
    public static String getUserName(String pkg){
        List<String> list = Shell.runCmdAndGetResult("su -c ls -l /data/data/");
        if(list != null) {
        	for(String str : list){
        		if(str.endsWith(pkg)){
        			String[] ss = str.split("\\s+");
        			return ss[1];
        		}
        	}
        }
        return null;
    }
}
